<template>
  <div class="uploadimg">
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="requestHandler"
    >
      <template v-if="value">
        <img :src="value" class="avatar">
        <i class="el-icon-close" @click.self.stop="clearImg" />
      </template>
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
const COS = require('cos-js-sdk-v5')

// 实例化
const cos = new COS({
  SecretId: 'AKIDIQHtEj27xXsxnOjphKhogIfmdGfpjOoy', // 身份识别 ID
  SecretKey: 'xf8LI9l7D4g290cz6yc081e3C6k9IBoD' // 身份密钥
})
export default {
  name: 'Uploadimg',
  props: {
    value: String
  },

  data() {
    return {
      //   imageUrl: ''
    }
  },
  methods: {
    // 删除照片
    clearImg() {
      this.$emit('input', '')
    },
    requestHandler(params) {
      // 在需求的时候调用方法即可
      //   console.log('asdasda', params)
      cos.putObject(
        {
          Bucket: 'storage-1308609337' /* 容器名 必须 */,
          Region: 'ap-hongkong' /* 存储桶所在地域，必须 */,
          Key: params.file.name /* 文件标记,可以用名字代替 必须 */,
          StorageClass: 'STANDARD' /* 固定值可以不管他 必须 */,
          Body: params.file, // 上传文件对象
          onProgress: (progressData) => {
            // 上传进度
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(data)
          // 有错就是err 没错就是 data
          console.log(err || data)
          if (data.statusCode === 200) {
            this.$emit('input', 'https://' + data.Location)
          }
        }
      )
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isImg = ['image/jpeg', 'image/gif', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImg) {
        this.$message.error('上传头像图片只能是 Img 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImg && isLt2M
    }
  }
}
</script>

<style lang="scss">
.uploadimg {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    // overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-icon-close {
    content: '\e6db';
    position: absolute;
    top: -9px;
    right: -10px;
    font-size: 20px;
  }
}
</style>
